package com.lechi.web.controller;

import com.lechi.web.common.annotation.Log;
import com.lechi.web.common.core.controller.BaseController;
import com.lechi.web.common.core.domain.AjaxResult;
import com.lechi.web.common.core.page.TableDataInfo;
import com.lechi.web.common.enums.BusinessType;
import com.lechi.web.common.enums.ErrorCodeEnum;
import com.lechi.web.common.exception.ServiceException;
import com.lechi.web.common.utils.StringUtils;
import com.lechi.web.constants.Constants;
import com.lechi.web.service.IIotScheduleJobService;
import com.lechi.web.system.domain.IotScheduleJobBo;
import com.lechi.web.vo.IotScheduleJobQueryVo;
import com.lechi.web.vo.IotScheduleJobVo;
import jakarta.validation.Valid;
import org.quartz.CronExpression;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

/**
 * 调度任务信息操作处理
 *
 * @author yg
 */
@RestController
@RequestMapping("/iot/job")
public class IotScheduleJobController extends BaseController {

    @Autowired
    private IIotScheduleJobService iotScheduleJobService;

    /**
     * 查询定时任务列表
     */
    @GetMapping("/list")
    public TableDataInfo list(IotScheduleJobQueryVo jobVo) {
        startPage();
        IotScheduleJobBo job = new IotScheduleJobBo();
        BeanUtils.copyProperties(jobVo, job);
        List<IotScheduleJobBo> list = iotScheduleJobService.selectJobList(job);
        return getDataTable(list);
    }

    /**
     * 新增定时任务
     */
//    @PreAuthorize("@ss.hasPermi('monitor:job:add')")
    @Log(title = "定时任务", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult add(@RequestBody @Valid IotScheduleJobVo jobVo) {
        IotScheduleJobBo job = new IotScheduleJobBo();
        BeanUtils.copyProperties(jobVo, job);
        job.setCreateBy(getUsername());
        Optional<String> optional = Optional.empty();
        LocalDate today = LocalDate.now();
        LocalDate tomorrow = today.plusDays(1).plusMonths(1);
        String hour = "multi".equals(job.getMisfirePolicy()) ? Constants.DAY.equals(job.getCheckType()) ? "0" : "*"
                : Constants.DAY.equals(job.getCheckType()) ? "0" : String.valueOf(tomorrow.getDayOfMonth());
        String day = "multi".equals(job.getMisfirePolicy()) ? "*" : Constants.DAY.equals(job.getCheckType()) ? String.valueOf(tomorrow.getDayOfMonth())
                : String.valueOf(today.getDayOfMonth());
        String month = "multi".equals(job.getMisfirePolicy()) ? "*" : String.valueOf(tomorrow.getMonthValue());
        optional = Optional.ofNullable(StringUtils.format("0 {} {} {} {} ? ", job.getDelayTime(), hour, day, month));
        optional.filter(CronExpression::isValidExpression).orElseThrow(() -> new ServiceException(ErrorCodeEnum.CMD_PARSE_CREATE_ERROR.getValue(), ErrorCodeEnum.CMD_PARSE_CREATE_ERROR.getKey()));
        optional.ifPresent(job::setCronExpression);
        return toAjax(iotScheduleJobService.insertJob(job));
    }

    /**
     * 定时任务状态修改
     */
//    @PreAuthorize("@ss.hasPermi('monitor:job:changeStatus')")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody IotScheduleJobBo job) {
        IotScheduleJobBo newJob = iotScheduleJobService.selectJobById(job.getId());
        newJob.setStatus(job.getStatus());
        return toAjax(iotScheduleJobService.changeStatus(newJob));
    }

    /**
     * 定时任务立即执行一次
     */
//    @PreAuthorize("@ss.hasPermi('monitor:job:changeStatus')")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PostMapping("/run")
    public AjaxResult run(@RequestBody IotScheduleJobBo job) {
        boolean result = iotScheduleJobService.run(job);
        return result ? success() : error("任务不存在或已过期！");
    }

    /**
     * 删除定时任务
     */
//    @Log(title = "定时任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{jobIds}")
    public AjaxResult remove(@PathVariable Long[] jobIds) {
        iotScheduleJobService.deleteJobByIds(jobIds);
        return success();
    }
}
